package com.yb.personelmanagement.controller.system;

import com.yb.personelmanagement.config.jwt.JwtTokenUtil;
import com.yb.personelmanagement.domain.System.PageResult;
import com.yb.personelmanagement.domain.System.Result;
import com.yb.personelmanagement.domain.System.StatusCode;
import com.yb.personelmanagement.domain.System.User;
import com.yb.personelmanagement.service.jwt.JwtUserDetailsService;
import com.yb.personelmanagement.service.system.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * @Auther: lzx
 * @Date: 2019/8/8 12:40
 * @Description: 用户相关请求接口
 */
@RestController
@Api(value = "用户管理", description = "用户管理")
public class UserController {
	@Autowired
	UserService userService;
	@Autowired
	JwtUserDetailsService userDetailsService;
	@Autowired
	JwtTokenUtil jwtTokenUtil;

	@Value("${jwt.header}")
	private String tokenHeader;

	@ApiOperation(value = "查询用户列表，不带分页")
	@GetMapping("/user/findAll")
	public Result findAll() {
		return userService.findAllUser();
	}

	@RequestMapping(value = "user", method = RequestMethod.GET)
	public User getAuthenticatedUser(HttpServletRequest request) {
		String token = request.getHeader(tokenHeader).substring(7);
		String username = jwtTokenUtil.getUsernameFromToken(token);
		User user = userDetailsService.loadUserByUsername(username);
		return user;
	}

	@PostMapping("/user")
	public Result addUser(@RequestBody User user) {

		return userService.addUser(user);
	}

	public Result findById(Long id) {
		return userService.findById(id);
	}

	/**
	 * 条件查询
	 * 
	 * @param searchMap
	 * @return
	 */
	@RequestMapping(value = "/search", method = RequestMethod.POST)
	public Result findSearch(@RequestBody Map searchMap) {
		return new Result(true, userService.findSearch(searchMap), "查询成功", StatusCode.SUCCESS);
	}

	/**
	 * 带条件分页查询
	 * 
	 * @param searchMap
	 * @param page
	 * @param size
	 * @return
	 */
	@RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
	public Result findSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
		Page pageList = userService.findSearch(searchMap, page, size);
		return new Result(true, new PageResult(pageList.getTotalElements(), pageList.getContent()), "查询成功",
				StatusCode.SUCCESS);
	}
}
